/**
 * Copyright 2011 Clemens Lombriser <clemens@lom.ch>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */

package ch.lom.clemens.android.bibliography;

import ch.lom.clemens.android.bibliography.data.JSONWebConnector;
import ch.lom.clemens.android.bibliography.data.MendeleyConnector;
import oauth.signpost.OAuth;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.Toast;

public class StartActivity extends TabActivity implements OnSharedPreferenceChangeListener {

	public static MendeleyConnector m_mendeley;
	public static StartActivity singleton;
	
	public final static String TAB_COLLECTIONS = "Collections";
	public final static String TAB_DOCUMENTS   = "Documents";
	public final static String TAB_DOCUMENT    = "Document";
	
	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_PROGRESS);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.startactivity);
        
        singleton = this;
        if (m_mendeley==null) {
        	m_mendeley = new MendeleyConnector(this);
        }
        
        TabHost tabHost = getTabHost();
        
        Intent intent = new Intent().setClass(this, CollectionsActivity.class);
        TabHost.TabSpec spec = tabHost.newTabSpec(TAB_COLLECTIONS).setIndicator("Collections", getResources().getDrawable(R.drawable.docorgs)).setContent(intent);
        tabHost.addTab(spec);
        
        intent = new Intent().setClass(this, DocumentsActivity.class);
        //spec = tabHost.newTabSpec(TAB_DOCUMENTS).setIndicator("Documents", getResources().getDrawable(android.R.drawable.ic_dialog_email)).setContent(intent);
        spec = tabHost.newTabSpec(TAB_DOCUMENTS).setIndicator("Documents", getResources().getDrawable(R.drawable.collection)).setContent(intent);
        tabHost.addTab(spec);
        
        intent = new Intent().setClass(this, DocumentActivity.class);
        //spec = tabHost.newTabSpec(TAB_DOCUMENT).setIndicator("Document", getResources().getDrawable(android.R.drawable.ic_dialog_info)).setContent(intent);
        spec = tabHost.newTabSpec(TAB_DOCUMENT).setIndicator("Document", getResources().getDrawable(R.drawable.document)).setContent(intent);
        tabHost.addTab(spec);
        
        tabHost.setCurrentTab(0);
    }
    
    
    // //////////////////////////////////////////////////////////////////////////
    // Preferences
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.mainmenu, menu);
    	
    	menu.getItem(0).setIcon(android.R.drawable.ic_menu_preferences);
    	menu.getItem(1).setIcon(android.R.drawable.ic_menu_info_details);
    	
    	return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {

    	boolean retVal = true;
    	
    	switch(item.getItemId()) {
    		case R.id.menuPreferences:
    			
    			Intent setint = new Intent(getApplicationContext(), MainPreferences.class);
    			startActivity(setint);
    			
    			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    			pref.registerOnSharedPreferenceChangeListener(this);
    			
    		    //ListPreference lprf = (ListPreference).findPreference("preference_pdfpath");
    			
    		
    			break;
    		case R.id.menuInfo:
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			builder.setMessage("This App connects to the Mendeley bibliography database.\n\nCreated by Clemens Lombriser, 2011")
    					.setNeutralButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						});
    			AlertDialog about = builder.create();
    			about.show();
    			break;
			default:
				retVal = false;
				break;
    	}
    	
    	return retVal;
    }
    
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
		
		if (getString(R.string.preference_pdfpath).equals(key)) {
			DocumentActivity.DOCSDIR = sharedPreferences.getString(key, DocumentActivity.DOCSDIR);
		}
		
		
	}
    

    // //////////////////////////////////////////////////////////////////////////
    // OAuth helpers
    
	public static final int MENDELEY_RETRIEVE_COLLECTIONS = 1;
	public static final int MENDELEY_RETRIEVE_COLLECTION  = 2;
	public static final int MENDELEY_RETRIEVE_DOCUMENT    = 3;
    private static int m_authcallingtask = -1;

    /** Starts the OAuth authentication process over the browser, and returns to the calling function */
    public void doAuthentication(int callingtask) {
    	try {
    		m_authcallingtask = callingtask;
    		String authURL = StartActivity.m_mendeley.getAuthenticationURL();
    		
    		if (authURL != null) startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
		} catch(Exception e) {
			Toast.makeText(getApplicationContext(), "Got exception while authenticating:\n" + e.getMessage(), Toast.LENGTH_LONG);
			Log.d("OAuthMendeley","Got exception while authenticating:\n" + e.getMessage());
		}
    }

    public void onResume() {
    	super.onResume();
    	
    	Uri uri = this.getIntent().getData();
    	
    	// finish authentication if requested
    	if (uri != null && uri.toString().startsWith(JSONWebConnector.CALLBACK)) {
    		String code = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
    		
    		StartActivity.m_mendeley.setVerificationCode(code);
    		
    		switch(m_authcallingtask) {
	    		case MENDELEY_RETRIEVE_COLLECTIONS:
	    			CollectionsActivity.singleton.retrieveCollections();
	    			break;
	    		case MENDELEY_RETRIEVE_COLLECTION:
	    		case MENDELEY_RETRIEVE_DOCUMENT:
	    			// the view will automatically refresh itself and get the data
	    			getTabHost().setCurrentTabByTag(TAB_DOCUMENTS);
	    			break;
    			default:
    				Log.d("OAuthMendeley","Resuming with unknown callingtask");
    				break;
    		}
			m_authcallingtask = -1;
    		
    	} 
    }

}
